﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;

namespace WinSilver
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private ManagedWinapi.Hotkey hotkey;

        private static Window win;

        protected override void OnStartup(StartupEventArgs e)
        {
            // To prevent start at launch, remove the startup URI in app.xaml

            hotkey = new ManagedWinapi.Hotkey();
            hotkey.Alt = true;
            hotkey.KeyCode = System.Windows.Forms.Keys.Space;
            hotkey.HotkeyPressed += new EventHandler(hotkey_HotkeyPressed);

            ShutdownMode = ShutdownMode.OnExplicitShutdown;

            try
            {
                hotkey.Enabled = true;
            }
            catch (ManagedWinapi.HotkeyAlreadyInUseException)
            {
                System.Windows.MessageBox.Show("Could not register hotkey (already in use).", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            base.OnStartup(e);
        }

        void hotkey_HotkeyPressed(object sender, EventArgs e)
        {
            if (win == null)
            {
                //MessageBox.Show("create win");

                win = new MainWindow();
                win.Closed += new EventHandler(win_Closed);

                // do not change the order of the following
                win.Show();
                win.Activate();
                
                try
                {
                    win.Focus();
                }
                catch (Exception)
                {
                }
            }
            else
            {
                win.Activate();
            }
        }

        void win_Closed(object sender, EventArgs e)
        {
            win = null;
        }

        protected override void OnExit(ExitEventArgs e)
        {
            hotkey.Dispose();
            base.OnExit(e);
        }
    }
}
